package Batch::Simple;
use strict;
use warnings;
use Moose;
use Batch::Simple::Result;
use autodie qw{open close};
use File::Temp;
use Modern::Perl;

our $VERSION = '0.01';


has 'command' => (
  is => 'rw',
  isa => 'Str',
  required => 1,
);


has 'options' => (
  is => 'rw',
  isa => 'ArrayRef[Str]',
  default => sub { [] },
);


has 'input' => (
  is => 'rw',
  isa => 'Str',
  clearer   => 'clear_input',
  predicate => 'has_input',
);


around BUILDARGS => sub {    #actuar sobre la forma del constructor 
      my $orig = shift;
      my $class = shift;

      if ( @_ == 1 && ! ref $_[0] ) {
          return $class->$orig(command => $_[0]);
      }
      else {
          return $class->$orig(@_);
      }
  };


sub run {
  my $self = shift;

  my $teh = File::Temp->new();
  my $ten = $teh->filename();


  my $savein;
  if ($self->has_input) {
    open $savein, '<&', \*STDIN;
    my $inputname = $self->input;
    die "Error in Batch::Simple::run. Can't find input file '$inputname'\n" unless -r $inputname;
    open STDIN, '<', $inputname;
  }
  open my $saveerr, ">& STDERR";  

    open STDERR, ">&", $teh;

      my $perlWarnings = '';

        my ($command, @options) = ($self->command, @{$self->options});  #obtenemos el comando y las opciones
        my $out = do {   #ejecución del qx, do evlaua el conjunto de setencias, la última sentencia ejecutada es el qx
          local $SIG{'__WARN__'} = sub { $perlWarnings .= $_[0] }; #cada vez que se produzca una señal de warning se lanza una subrutina anónima que concatena los warning
          qx{$command @options};  
        };

        $out = '' unless defined($out); 

        my $status = $?;

    close($teh); # and close STDERR

    open my $eh, "<", $ten;  
      my $err = join '', <$eh>;  
    close($eh);
    $err .= $perlWarnings;  #añadimos los warning de pel

  open STDERR, '>&', $saveerr; # restore STDERR  #restauramos los valores
  open STDIN,  '<&', $savein if $self->has_input;  #restauramos los valores

  my $r = Batch::Simple::Result->new(stdout => $out, stderr => $err, status => $status);
  return $r;
}






# Preloaded methods go here.

#sub run {
 #  my $self = shift;

   #salvar stderr
  # open my $saverr, '>&', \*STDERR;

   #redirigir stderr al fichero temporal
   #my $htemperr = File::Temp -> new(); #fichero temporal
   #open \*STDERR, '>&'. &htempnew;

  # my $command = $self -> command;
  # my $out = qx{$command};

  # my $teh = File::Temp-> new; my $ten = $teh -> filename;
  # my $savein;
  # if ($self -> has_input) {
  #    open &savein;
   #   my $inputname = $self -> input;
    #  die "error..................." unless -r $inputname;
     # open STDIN, '<', $savein;
   #}
#}



1;
__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

Batch::Simple - Perl extension for blah blah blah

=head1 SYNOPSIS

  use Batch::Simple;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for Batch::Simple, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.

=head2 EXPORT

None by default.



=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

If you have a mailing list set up for your module, mention it here.

If you have a web site set up for your module, mention it here.

=head1 AUTHOR

RODRIGUEZ VARGAS, E<lt>alu3724@E<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2011 by RODRIGUEZ VARGAS

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.0 or,
at your option, any later version of Perl 5 you may have available.


=cut
